package com.ruoyi.web.controller.app;

import com.ruoyi.business.domain.TMessage;
import com.ruoyi.business.domain.TMessageRead;
import com.ruoyi.business.service.ITMessageReadService;
import com.ruoyi.business.service.ITMessageService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * B端 消息中心接口
 */
@RestController
@RequestMapping("/b-api/message")
public class BapiMessageController extends BaseController {

    @Autowired
    private ITMessageService messageService; // 代码生成器已创建

    @Autowired
    private ITMessageReadService messageReadService; // 代码生成器已创建

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    /**
     * 获取B端用户消息列表
     */
    @GetMapping("/list")
    public TableDataInfo list() {
        Long userId = SecurityUtils.getUserId();
        SysUser user = userService.selectUserByUserName(SecurityUtils.getUsername());
        Set<String> roles = permissionService.getRolePermission(user);

        // 步骤1：根据用户角色和ID筛选消息
        TMessage queryParam = new TMessage();
        // 在Service层处理复杂的权限逻辑

        startPage();
        // 假设我们会在Service层处理根据角色筛选消息的逻辑
        List<TMessage> list = messageService.selectBapiMessageList(queryParam);

        // 步骤2：判断已读状态
        if (list != null && !list.isEmpty()) {
            // 获取当前用户的所有已读消息ID
            List<TMessageRead> readRecords = messageReadService.selectTMessageReadListByUserId(userId);
            Set<Long> readMessageIds = readRecords.stream()
                    .map(TMessageRead::getMessageId)
                    .collect(Collectors.toSet());

            // 遍历消息列表，标记是否已读
            for (TMessage message : list) {
                if (readMessageIds.contains(message.getMessageId())) {
                    message.getParams().put("isRead", true);
                } else {
                    message.getParams().put("isRead", false);
                }
            }
        }

        return getDataTable(list);
    }

    /**
     * 标记消息为已读
     */
    @PostMapping("/read/{messageId}")
    public AjaxResult readMessage(@PathVariable("messageId") Long messageId) {
        Long userId = SecurityUtils.getUserId();

        // 步骤1：检查是否已经已读
        TMessageRead queryParam = new TMessageRead();
        queryParam.setMessageId(messageId);
        queryParam.setUserId(userId);
        List<TMessageRead> existRecords = messageReadService.selectTMessageReadList(queryParam);

        // 如果记录不存在，才进行插入
        if (existRecords == null || existRecords.isEmpty()) {
            TMessageRead record = new TMessageRead();
            record.setMessageId(messageId);
            record.setUserId(userId);
            record.setReadTime(new Date()); // 可以直接在service或mapper中设置

            messageReadService.insertTMessageRead(record);
        }

        return AjaxResult.success("标记已读成功");
    }
}